<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">			
			.box{width: 100px;height: 100px;background: green;position: fixed;cursor: pointer;right: 10px;}
		</style>
	</head>
	<body>
		<div class="box" id="drag"></div>
	</body>
	<script type="text/javascript">
		
		window.onload = function()
		{
			dragDiv("drag");
		};
		
		function dragDiv(id){
			var oDiv = document.getElementById(id);
			var disX = 0;
			var disY = 0;
			
			oDiv.onmousedown = function(ev)   //这里把oDiv换成document，鼠标的指针移出div时，也跟随移动
			//document.onmousedown = function(ev)
			{
				var oEvent = ev||event;
				//记录鼠标的坐标
				disX = oEvent.clientX - oDiv.offsetLeft;
				disY = oEvent.clientY - oDiv.offsetTop;
				
				document.onmousemove = function(ev){
					var oEvent = ev||event;
					//设置div的位置跟随鼠标
					
					var l = oEvent.clientX - disX;
					var t = oEvent.clientY - disY;
					
					if (l <5){
						l = 0;
					}else if(l > document.documentElement.clientWidth - oDiv.offsetWidth){
						l = document.documentElement.clientWidth - oDiv.offsetWidth;
					}
					
					if (t <5){
						t = 0;
					}else if(t > document.documentElement.clientHeight - oDiv.offsetHeight){
						t = document.documentElement.clientHeight - oDiv.offsetHeight;
					}
					oDiv.style.left = l + "px";
					oDiv.style.top = t + "px";
				};
				
				document.onmouseup = function(){
					//清除函数
					document.onmousemove = null;
					document.onmouseup = null;
				};
				
			};
		}
		
	</script>
</html>
